class WebSocketManager {
    constructor() {
        this.ws = null;
        this.baseUrl = 'ws://localhost:3000';
        this.isConnected = false;
        this.messageCallback = null;
        this.reconnectTimer = null;
        this.reconnectAttempts = 0;
        this.maxReconnectAttempts = 5;
        this.currentSessionId = null;
    }

    connect() {
        if (this.ws) {
            this.ws.close();
            this.ws = null;
        }

        const token = wx.getStorageSync('token');
        if (!token) {
            console.error('未找到token，无法建立WebSocket连接');
            return;
        }

        try {
            this.ws = wx.connectSocket({
                url: `${this.baseUrl}?token=${encodeURIComponent(token)}`,
                header: {
                    'content-type': 'application/json'
                }
            });

            this.initEventHandlers();
        } catch (error) {
            console.error('创建WebSocket连接时发生错误：', error);
            this.reconnect();
        }
    }

    initEventHandlers() {
        if (!this.ws) return;

        this.ws.onOpen(() => {
            console.log('✅ WebSocket已连接');
            this.isConnected = true;
            this.reconnectAttempts = 0;
        });

        this.ws.onMessage((res) => {
            try {
                const data = JSON.parse(res.data);
                console.log('📤 收到消息:', data);
                if (this.messageCallback) {
                    this.messageCallback(data);
                }
            } catch (error) {
                console.error('🛑 解析消息失败:', error);
            }
        });

        this.ws.onClose(() => {
            console.log('❌ WebSocket已关闭');
            this.isConnected = false;
            this.reconnect();
        });

        this.ws.onError((error) => {
            console.error('⚠️ WebSocket错误:', error);
            this.isConnected = false;
            this.reconnect();
        });
    }

    // 设置消息回调
    onMessage(callback) {
        this.messageCallback = callback;
    }

    // 初始化聊天
    initChat(productId) {
        return this.send('initChat', { productId });
    }

    // 发送消息
    sendMessage(content, type = 'text') {
        if (!this.currentSessionId) {
            return Promise.reject(new Error('未初始化聊天会话'));
        }
        return this.send('sendMessage', {
            sessionId: this.currentSessionId,
            content,
            type
        });
    }

    // 获取历史消息
    getHistory(before = null, limit = 20) {
        if (!this.currentSessionId) {
            return Promise.reject(new Error('未初始化聊天会话'));
        }

        return new Promise((resolve, reject) => {
            // 创建一个一次性的消息处理器来接收历史消息
            const historyHandler = (data) => {
                if (data.type === 'history') {
                    // 收到历史消息后，移除这个处理器
                    this.messageCallback = null;
                    resolve(data);  // 直接返回完整的消息对象
                }
            };

            // 临时保存当前的消息处理器
            const originalCallback = this.messageCallback;

            // 设置历史消息处理器
            this.messageCallback = historyHandler;

            // 发送获取历史消息的请求
            this.send('getHistory', {
                sessionId: this.currentSessionId,
                before,
                limit
            }).catch(error => {
                // 发送失败时，恢复原来的消息处理器
                this.messageCallback = originalCallback;
                reject(error);
            });
        });
    }

    send(type, data = {}) {
        if (!this.isConnected || !this.ws) {
            console.error('WebSocket未连接');
            return Promise.reject(new Error('WebSocket未连接'));
        }

        const message = JSON.stringify({ type, data });
        return new Promise((resolve, reject) => {
            this.ws.send({
                data: message,
                success: () => {
                    console.log(`📤 发送${type}成功:`, data);
                    resolve(true);
                },
                fail: (error) => {
                    console.error(`📤 发送${type}失败:`, error);
                    reject(error);
                }
            });
        });
    }

    reconnect() {
        if (this.reconnectTimer || this.reconnectAttempts >= this.maxReconnectAttempts) {
            return;
        }

        this.reconnectAttempts++;
        console.log(`🔄 尝试第${this.reconnectAttempts}次重连...`);

        this.reconnectTimer = setTimeout(() => {
            this.reconnectTimer = null;
            this.connect();
        }, 3000);
    }

    close() {
        if (this.reconnectTimer) {
            clearTimeout(this.reconnectTimer);
            this.reconnectTimer = null;
        }

        if (this.ws) {
            this.ws.close({
                reason: '主动关闭连接'
            });
            this.ws = null;
        }

        this.isConnected = false;
        this.messageCallback = null;
        this.currentSessionId = null;
    }

    setSessionId(sessionId) {
        this.currentSessionId = sessionId;
    }
}

export default new WebSocketManager();